<template>
	<div class="search-vue">
		<!-- 搜索标题 -->
		<van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />

		<!-- 搜索框 -->
		<van-search
			v-model="inputVal"
			shape="round"
			show-action
			placeholder="请输入搜索关键词"
			@search="onSearch"
			@input="onInput"
		>
			<template #action>
				<div @click="onSearch">搜索</div>
			</template>
		</van-search>

		<!-- 历史记录 -->
		<van-cell-group v-if="inputVal == ''">
			<van-cell title="历史记录" />
			<van-cell
				v-for="(item, index) in hisKeysList"
				:key="index"
				:title="item"
                @click="$router.push(`/search/result?key=${item}`)"
			/>
		</van-cell-group>

		<!-- 联想词 -->
		<van-cell-group v-else>
			<van-cell
				@click="$router.push(`/search/result?key=${assKeysList[index]}`)"
				icon="search"
				v-for="(item, index) in colorList"
				:key="index"
			>
				<div v-html="item">{{ item }}</div>
			</van-cell>
		</van-cell-group>
	</div>
</template>

<script>
import { AssKeysAPI } from "@/api/search";
export default {
	data() {
		return {
			inputVal: "",
			assKeysList: [],
			hisKeysList: JSON.parse(localStorage.getItem("historyKeys")) || [],
		};
	},
	methods: {
		// 点击搜索
		onSearch() {
			// 非空判断
			if (this.inputVal == "") return this.$toast("请输入搜索内容");

			// 先把输入的内容存到数组里
			if (this.hisKeysList.indexOf(this.inputVal) == -1) {
				this.hisKeysList.unshift(this.inputVal);
			}
			// 把数组保存到本地存储
			localStorage.setItem("historyKeys", JSON.stringify(this.hisKeysList));

			this.$router.push({
				name: "result",
				query: {
					key: this.inputVal,
				},
			});
		},
		// 输入搜索
		async onInput() {
			// 输入框为空，则不请求接口
			if (this.inputVal != "") {
				const res = await AssKeysAPI({
					q: this.inputVal,
				});
				// console.log(res);
				this.assKeysList = res.data.options;
			}
		},
	},
	computed: {
		// 匹配颜色高亮
		colorList() {
			return this.assKeysList.map((v) => {
				// 将内容相同的字母替换成带有标签的字母
				return v.replaceAll(
					this.inputVal,
					`<span style="color:red">${this.inputVal}</span>`
				);
			});
		},
	},
};
</script>

<style>
</style>